package quick.start.core.io;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.io.Serializable;
import java.io.StreamCorruptedException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class ObjectToFile {

	public static boolean writeToFile(Serializable obj, String path, String fileName) throws FileNotFoundException, IOException{
		boolean fileExists = forceNewFile(path, fileName);
		if(!fileExists)
			return false;
		
		File file = new File(path, fileName);
		FileOutputStream fileOutput = new FileOutputStream(file);
		BufferedOutputStream bufferOutput = new BufferedOutputStream(fileOutput);
		ObjectOutputStream output = new ObjectOutputStream(bufferOutput);
		output.writeObject(obj);
		IOUtils.closeQuietly(output);
		return true;
	}
	
	public static <T> T readFromFile(Class<T> cls, String path, String fileName){
        ObjectInputStream objectInputStream = null;
        try {
            byte[] bytes = FileUtils.readFileToByteArray(new File(path, fileName));
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            objectInputStream = new ObjectInputStream(byteArrayInputStream);
            return cls.cast(objectInputStream.readObject());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (OptionalDataException e) {
            e.printStackTrace();
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(objectInputStream);
        }
        return null;
	}
	
	public static boolean forceNewFile(String path, String fileName){
        try {
            FileUtils.forceMkdir(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        File file = new File(path, fileName);
        if (!file.exists()) {
            try {
                return file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
	}
}
